
package com.william.killian.trivia;

import java.io.File;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.william.killian.trivia.model.Answer;
import com.william.killian.trivia.model.HighScoreList;
import com.william.killian.trivia.model.Question;
import com.william.killian.trivia.model.Quiz;
import com.william.killian.trivia.util.Util;

public class Trivia extends ListActivity
{
    
    private Quiz quiz;

    private HighScoreList highScores;
    
    private ListView questionList;

    private GetNextQuestion nextQuestion;
    
    private static class LayoutUtility
    {
        private static TextView number;

        private static TextView question;

        private static ViewGroup header;

        private static ViewGroup footer;

        public static void Update (Quiz q)
        {
            number.setText (Integer.toString (q.getCurrentQuestionNumber ()));
            question.setText (q.getCurrentQuestion ().getText ());
        }

        public static void buildHeaderAndFooter (ListView questionList, LayoutInflater inflater)
        {
            header = (ViewGroup) inflater.inflate (R.layout.question_header, questionList, false);
            header.setFocusable (false);
            header.setFocusableInTouchMode (false);
            header.setClickable (false);
            header.setLongClickable (false);
            header.setSelected (false);

            footer = (ViewGroup) inflater.inflate (R.layout.question_footer, questionList, false);
            footer.setFocusable (false);
            footer.setFocusableInTouchMode (false);
            footer.setClickable (false);
            footer.setLongClickable (false);
            footer.setSelected (false);

            questionList.addHeaderView (header);
            questionList.addFooterView (footer);

            number = (TextView) header.findViewById (R.id.questionNumber);
            question = (TextView) header.findViewById (R.id.question);
        }
    }

    public void onCreate (Bundle savedInstanceState)
    {
        super.onCreate (savedInstanceState);
        setTheme (android.R.style.Theme_Light);
        questionList = getListView ();
        nextQuestion = new GetNextQuestion ();

        LayoutInflater inflater = getLayoutInflater ();
        LayoutUtility.buildHeaderAndFooter (questionList, inflater);
        setContentView (questionList);
        
        Bundle extras = getIntent ().getExtras ();
        if (extras != null)
        {
            quiz = (Quiz) extras.get ("quiz");
            if (quiz == null)
            {
                Util.ShowErrorDialog (this);
            }
            else if (quiz.getQuestions ().size () < 1)
            {
                new AlertDialog.Builder (this)
                    .setTitle (R.string.error)
                    .setMessage (R.string.text_quiz_empty)
                    .setPositiveButton (R.string.close, new Returner ())
                    .show ();
            }
            else
            {
                highScores = loadHighScores ();
                quiz.start ();
                getNextQuestion ();
            }
        }
        else
        {
            finish ();
        }
    }
    
    private HighScoreList loadHighScores()
    {
        File file = quiz.getHighScoreFile ();
        return HighScoreList.Load (file);
    }
    
    public void endQuiz ()
    {
        int correct = quiz.getNumberOfCorrectAnswers ();
        int total = quiz.getNumberOfQuestions ();
        int percent =  quiz.getQuizPercentage ();
        new AlertDialog.Builder (Trivia.this)
            .setTitle (R.string.text_dialog_quiz_over)
            .setMessage (correct + "/" + total + "  " + percent + "%\n" + getString (R.string.text_submit))
            .setIcon (R.drawable.ic_question)
            .setPositiveButton (R.string.yes, new Submitter())
            .setNegativeButton (R.string.no, new Returner())
            .show ();
            
    }

    public void checkAnswer (View v)
    {
        final SparseBooleanArray submission = questionList.getCheckedItemPositions ();
        final Question curr = quiz.getCurrentQuestion ();
        boolean correct = true;

        for (int i = 0; i < curr.getAnswers ().size (); ++i)
        {
            boolean value = (submission.get (i + 1, false));
            correct = correct && (curr.getAnswers ().get (i).isSubmissionCorrect (value));
        }
        if (correct)
        {
            quiz.addCorrectAnswer ();
            new AlertDialog.Builder (Trivia.this)
                .setIcon (R.drawable.ic_check)
                .setTitle (R.string.correct)
                .setMessage (R.string.text_correct)
                .setPositiveButton (R.string.close, nextQuestion)
                .show ();
        }
        else
        {
            quiz.addWrongAnswer ();
            String msg = curr.getAnswerText ();
            new AlertDialog.Builder (Trivia.this)
                .setIcon (R.drawable.ic_cross)
                .setTitle (R.string.incorrect)
                .setMessage (msg)
                .setPositiveButton (R.string.close, nextQuestion)
                .show ();
        }
    }

    private void getNextQuestion ()
    {
        Question next = quiz.getNextQuestion ();
        int layoutType;
        if (next.hasMultipleAnswers ())
        {
            questionList.setChoiceMode (ListView.CHOICE_MODE_MULTIPLE);
            layoutType = R.layout.multiple_choice;
        }
        else
        {
            questionList.setChoiceMode (ListView.CHOICE_MODE_SINGLE);
            layoutType = R.layout.single_choice;
        }
        questionList.setAdapter (new ArrayAdapter <Answer> (Trivia.this, layoutType, next.getAnswers ()));
        questionList.setFadingEdgeLength (10);
        questionList.setVerticalFadingEdgeEnabled (true);
        LayoutUtility.Update (quiz);
    }
    
    private class GetNextQuestion implements DialogInterface.OnClickListener
    {
        public void onClick (DialogInterface arg0, int arg1)
        {
            Trivia.this.setTitle (quiz.getNumberOfCorrectAnswers () + "/" + quiz.getCurrentQuestionNumber ());
            if (quiz.hasNextQuestion ())
            {
                getNextQuestion ();
            }
            else
            {
                endQuiz ();
            }
        }
    }
    
    private class Submitter implements DialogInterface.OnClickListener
    {
        public void onClick (DialogInterface arg0, int id)
        {
            final EditText input = new EditText (Trivia.this);  
            new AlertDialog.Builder (Trivia.this)
                .setTitle (R.string.title_submit)
                .setMessage (R.string.name)
                .setView (input)
                .setIcon (R.drawable.ic_check)
                .setPositiveButton (R.string.ok, new DialogInterface.OnClickListener()
                {
                    public void onClick (DialogInterface dialog, int which)
                    {
                        String name = input.getText().toString ();
                        int percentage = quiz.getQuizPercentage ();
                        highScores.add (percentage, name);
                        File newFile = quiz.getHighScoreFile ();
                        highScores.save (newFile);
                        Intent intent = new Intent(Trivia.this, HighScoreViewer.class);
                        intent.putExtra ("highscore", newFile);
                        startActivity (intent);
                        finish ();
                    }
                })
                .setNegativeButton (R.string.cancel, new Returner())
                .show ();
        }

    }
    
    private class Returner implements DialogInterface.OnClickListener
    {
        public void onClick (DialogInterface arg0, int id)
        {
            finish ();
        }
    }
    
}
